import Utils from "../../../../../Utils";
import { FacilityType } from "../../../../info/GameEnum";
import { Location } from "../../../../info/Predefine";
import { AiEnvironment } from "../../AiGameAction";
import { DecisionNode } from "../../DecisionTree";

/**
 * 建造视野设施
 */
export default class DecisionViewBuild extends DecisionNode {

    environment: AiEnvironment & { space: Location[] };

    spaces: Location[][];

    constructor(environment: AiEnvironment) {
        super(environment);
        this.childDecisionNodes.push(new DecisionBuildScoutBase(environment));
        this.childDecisionNodes.push(new DecisionBuildFlareBase(environment));
    }

    /**
     * 最多4个
     * 最低3分
     * 最高100
     * @returns 
     */
    evaluate(): number {
        this.spaces = this.environment.player.getSpaceBySize(1);
        if (this.spaces.length > 0) {
            let viewFacCount = 0;
            viewFacCount += this.environment.player.facilityArr[FacilityType.侦察机基地].length;
            viewFacCount += this.environment.player.facilityArr[FacilityType.照明弹基地].length;
            return Math.max(3, 100 - (viewFacCount * 25));
        } else {
            return 0;
        }
    }

    execute(): number {
        let selfMainhomeLocation = Utils.getRandomChoose(this.environment.player.facilityArr[FacilityType.主基地][0].locations);
        //每个建造地的得分，最低1分 最高 10分 离主基地越近得分越高
        let spaceScore: number[] = this.spaces.map(item => {
            let distanse = Math.min(10, Math.abs(selfMainhomeLocation.locationX - item[0].locationX) + Math.abs(selfMainhomeLocation.locationY - item[0].locationY));
            return 11 - distanse;
        })
        let index = Utils.getRandomIndexByProbability(spaceScore);
        this.environment.space = this.spaces[index];
        return super.execute();
    }
}

/**
 * 建造侦察机基地
 */
class DecisionBuildScoutBase extends DecisionNode {
    environment: AiEnvironment & { space: Location[] };

    /**
     * 两个侦察机基地以内，每个-45分
     * @returns 
     */
    evaluate(): number {
        if (!this.environment.player.checkFacilityCondition(FacilityType.侦察机基地).every(item => item)) return 0;
        let length = Math.min(2, this.environment.player.facilityArr[FacilityType.侦察机基地].length);
        return 5 + (100 - length * 50);
    }

    execute(): number {
        this.environment.player.addFacility(FacilityType.侦察机基地, this.environment.space);
        return 0;
    }
}
/**
 * 建造照明弹基地
 */
class DecisionBuildFlareBase extends DecisionNode {
    environment: AiEnvironment & { space: Location[] };
    evaluate(): number {
        if (!this.environment.player.checkFacilityCondition(FacilityType.照明弹基地).every(item => item)) return 0;
        let length = Math.min(2, this.environment.player.facilityArr[FacilityType.照明弹基地].length);
        return 5 + (100 - length * 50);
    }

    execute(): number {
        this.environment.player.addFacility(FacilityType.照明弹基地, this.environment.space);
        return 0;
    }
}